<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/28
 * Time: 10:32
 */

namespace app\adminapiv3\controller;

//安装
use app\adminapiv3\service\SystemConf;
use app\common\model\FilePath;
use think\Db;

class Install extends Base
{
    /**
     * 一. 同意协议
     * 二. 授权
     * 三. 数据库地址设置,生成数据库
     * 四. 添加代理服务器ip port
     * 五. 添加系统管理员
     * 六. 入库(授权信息)
     */
    private $installDir = './Install/';
    /**
     * @name 检查是否安装
     * @author wx
     * @date 2019/11/28 14:53
     */
    function isInstall()
    {
        $fileServer = new FilePath();
        $installFileName = $fileServer->install_path;


        if(!file_exists($this->installDir)){
            mkdir($this->installDir, 0777, true);
        }

        if (file_exists($installFileName)) {
            returnErrJson(121, '您已完成安装,请勿重复安装');
        }
    }


    /**
     * @name 在线授权
     * @author wx
     * @date 2019/11/28 10:55
     */
    function online()
    {
        $this->isInstall();

        //授权序列号
        $key = $this->filterInput('key*');

        $authServer = new \app\adminapiv3\service\ServerAuth();
        $serverInfo = $authServer->getPlatformBaseInfo();

        $requestData = array(
            'serial_number' => $key,
            'ip' => $_SERVER['SERVER_ADDR'],
            'system' => $serverInfo['os'],
            'alias' => $serverInfo['hostname'],
            'uuid' => $serverInfo['hostkey'],
        );

        $fileServer = new FilePath();
        $url = $fileServer->remote_auth_domain.'/api/v3/activation/register/online';

        $authRes = requestCurl($url,1,$requestData);

        if($authRes['code'] != 200){
            returnErrJson($authRes['code'], $authRes['msg']);
        }

        $server = new \app\adminapiv3\service\Install();
        $server->online($authRes);

        $this->jsonOutPut();
    }

    /**
     * @name 下载hostkey
     * @author wx
     * @date 2020/5/28 9:48
     */
    function getHostFile()
    {
        $data['ip'] = $_SERVER['SERVER_ADDR'];
        $data['port'] = $_SERVER['SERVER_PORT'];
        $data['path'] = 'static/host/hostkey.key';
        $data['url'] = $_SERVER['REQUEST_SCHEME'].'://' . $_SERVER['HTTP_HOST']  . '/static/host/hostkey.key';

        $server = new \app\adminapiv3\service\ServerAuth();
        $server->createHostFile();

        $this->jsonOutPut($data);
    }

    /**
     * @name 离线授权
     * @author wx
     * @date 2019/11/28 10:55
     */
    function offline()
    {
        $this->isInstall();

        $file = request()->file('file');


        if (!$file) {
            returnErrJson(122,'请上传授权文件');
        }

        $server = new \app\adminapiv3\service\Install();
        $server->toDo('offline',[$file]);

        $this->jsonOutPut();
    }


    /**
     * @name 获取模块
     * @author wx
     * @date 2020/1/8 20:37
     */
    function getModule()
    {
        $content = file_get_contents('./Install/auth.json');
        $arr = json_decode($content, true);


        $list = array();
        foreach ($arr as $k => $v) {

            if ($v['product_key'] != 'client') {//排除不需要端口的模块
                $tmp['name'] = $v['module_name'];
                $tmp['type'] = $v['product_key'];
                $list[] = $tmp;
            }

            $mode = $v['mode'];
        }
        $oldArr = array(
            array('name' => '代理','type' => 'proxy'),
            array('name' => '客户端','type' => 'client'),
        );

        $allArr = array_merge($list, $oldArr);

        $data['code'] = 200;
        $data['msg'] = 'success';
        $data['data'] = $allArr;
        $data['mode'] = $mode;
        echo json_encode($data);die;

    }


    /**
     * @name 设置代理服务器地址
     * @author wx
     * @date 2019/12/10 10:16
     */
    function addProxyIp()
    {
        $this->isInstall();

        $ip = $this->filterInput('ip*');
        $module = $this->filterInput('port');


        $server = new \app\adminapiv3\service\Install();
        $server->addProxy($ip, $module);

        $this->jsonOutPut();
    }


    /**
     * @name 用户名配置
     * @author wx
     * @date time
     */
    function userConfig()
    {
        $this->isInstall();

        $data['real_name'] = $this->filterInput('real_name*');
        $data['show_name'] = $this->filterInput('show_name*');
        $data['password'] = $this->filterInput('password*');
        $data['email'] = $this->filterInput('email*');

        $server = new \app\adminapiv3\service\Install();
        $stime = $server->adduser($data);

        //完成安装的事情
        $this->install($stime);
        $this->jsonOutPut();
    }

    /**
     * @name 安装完成的事情
     * @author wx
     * @date 2019/12/2 13:49
     */
    function install($stime)
    {

        $authPath = './Install/auth.json';
        if (!file_exists($authPath)) {
            returnErrJson(123, '您未授权,请先授权');
        }
        $content = file_get_contents($authPath);
        $authArr = json_decode($content, true);

        //1. 授权相关数据入库
        $authServer = new \app\adminapiv3\service\ServerAuth();
        $authServer->handleData($authArr, 1);


        //2. IP白名单入库
        $ip = $_SERVER['REMOTE_ADDR'];
        $allowIpInfo = db('server_allow_ip')->where('ip', $ip)->find();

        if(empty($allowIpInfo)){
            $addAllowIp['ip'] = $ip;
            $addAllowIp['ctime'] = time();
            $addAllowIp['login_time'] = 0;

            db('server_allow_ip')->insert($addAllowIp);
        }

        //3. ./Install/install.lock创建安装文件
        file_put_contents('./Install/install.lock','install finish time:'.date('Y-m-d H:i:s',time()));

        //4. 生成系统时间文件
        $nowTime = $stime > time() ? $stime : time();
        $data['stime'] = $nowTime;

        file_put_contents('./Install/system_time.json', json_encode($data));


    }
}